package com.jhd.fuzhou.view.daily;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.DocumentService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.BusinessStatus;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SearchUnit;
import com.jhd.fuzhou.vo.SupervisedUnitVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DocumentListActivity extends BaseActivity {
    private String type,unitName;//监督类型，1-日常监督  2-双随机 3-专项监督 4-量化评级
    @BindView(R.id.rv_record)RecyclerView rv_record;
    @BindView(R.id.tv_loading)TextView tv_loading;
    @BindView(R.id.tv_title)TextView tv_title;
    private SearchUnit searchUnit;
    private Context context=this;
    private LinearLayoutManager layoutManager;
    private Call<JsonForResult> jsonForResultCall;
    private List<SupervisionInspectionVo> supervisionInspectionVoList=new ArrayList<>();
    private DocumentAdapter documentAdapter;
    public ProgressDialog _dialog;
    private Gson gson=new Gson();
    private SupervisedUnitVo supervisedUnitVo;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_document_list);
    }

    @Override
    protected void processLogic() {
        onBack();
        type=getIntent().getStringExtra("type");
        supervisedUnitVo=JSON.parseObject(getIntent().getStringExtra("supervisionUnit"),SupervisedUnitVo.class);
        if("4".equals(type))tv_title.setText("评级记录");
        unitName=getIntent().getStringExtra("unitName");
        searchUnit=new SearchUnit();
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);//默认只有一页
        layoutManager = new LinearLayoutManager(context);
        rv_record.setLayoutManager(layoutManager);
        _dialog=new ProgressDialog(context);
        rv_record.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                        getList();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);//没到底部，隐藏
                }
            }
        });
        getList();
    }

    /*日常监督-superviseEnclosureVoList  双随机，专项监督-documentAttachmentList*/
    private void getList(){
        if(!_dialog.isShowing()){
            _dialog.setMessage("正在获取监督记录列表,请稍等...");
            _dialog.show();
        }
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        DocumentService vs = retrofit.create(DocumentService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize", 20);
        if(!("1".equals(application.getOrgLevel()))){
            if(application.getOrgId()!=null)params.put("superviseOrgId",application.getOrgId());
        }
        params.put("unitName", unitName);
        params.put("deptName", unitName);
        String ss=JSON.toJSONString(params);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        if("1".equals(type)){
            params.put("supervisedType", "0");
            jsonForResultCall = vs.getSupervisionInspectioList(application.getAccessToken(), params);
        }else if("2".equals(type)){
            jsonForResultCall = vs.getDoubleRandomManagementList(application.getAccessToken(), params);
        }else if("3".equals(type)){
            jsonForResultCall = vs.getSuperviseInspectionSpecialList(application.getAccessToken(), params);
        }else if("4".equals(type)){
            jsonForResultCall = vs.getGradeReportMstList(application.getAccessToken(), requestBody);
        }
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<SupervisionInspectionVo> supervisionInspectionVos = JSON.parseArray(jsonForResult.getData().toString(), SupervisionInspectionVo.class);
                            for (SupervisionInspectionVo supervisionInspectionVo : supervisionInspectionVos) {
                                supervisionInspectionVoList.add(supervisionInspectionVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                documentAdapter = new DocumentAdapter();
                                rv_record.setAdapter(documentAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                documentAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal() / 20 + 1);
                        } else {
                            documentAdapter = new DocumentAdapter();
                            rv_record.setAdapter(documentAdapter);
                            tv_loading.setText(context.getString(R.string.arrival_bottom));
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    if(_dialog != null)_dialog.cancel();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg+t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public class DocumentAdapter extends RecyclerView.Adapter<DocumentAdapter.ViewHolder> {
        @Override
        public DocumentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_document_list, parent, false);
            DocumentAdapter.ViewHolder viewHolder = new DocumentAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull DocumentAdapter.ViewHolder holder, int position) {
            holder.tv_time.setText(supervisionInspectionVoList.get(position).getReportDate().substring(0,10));
            if(!StringUtil.isNullOrEmpty(supervisionInspectionVoList.get(position).getFirstSupervisorName()))holder.tv_supervisorName.setText(supervisionInspectionVoList.get(position).getFirstSupervisorName());
            if(!StringUtil.isNullOrEmpty(supervisedUnitVo.getLegalRepresentative()))holder.tv_legalRepresentative.setText(supervisedUnitVo.getLegalRepresentative());
            if("4".equals(type)){
                holder.tv_status.setText(supervisionInspectionVoList.get(position).getGrade());
            }else{
                if("0".equals(supervisionInspectionVoList.get(position).getInspectResult())){
                    holder.tv_status.setTextColor(getResources().getColor(R.color.red));
                }
                holder.tv_status.setText("0".equals(supervisionInspectionVoList.get(position).getInspectResult())?"不合格":"合格");//检查结果(0-不合格 1-合格)
            }
            if("2".equals(type)){
                holder.tv_type.setVisibility(View.VISIBLE);
                holder.tv_type.setText("0".equals(supervisionInspectionVoList.get(position).getTaskType())?"国":"省");
            }
            holder.tv_speciality.setText(("4".equals(type)?supervisionInspectionVoList.get(position).getSpecialityCategoryName()+" - "+supervisionInspectionVoList.get(position).getDetailCategoryName():("2".equals(type)?supervisedUnitVo.getSpecialityCategory()+" - " + supervisedUnitVo.getSpecialityDetail():supervisionInspectionVoList.get(position).getSpecialityCategory() + " - " + supervisionInspectionVoList.get(position).getSpecialityDetail())));
            if (!StringUtil.isNullOrEmpty(supervisedUnitVo.getRegisterAddress())) {
                holder.unitAddress.setText(supervisedUnitVo.getRegisterAddress());
            }
            holder.tv_unitName.setText("4".equals(type)?supervisionInspectionVoList.get(position).getDeptName():("2".equals(type)?supervisionInspectionVoList.get(position).getSupervisedUnitName():supervisionInspectionVoList.get(position).getUnitName()));
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, DocumentDetailActivity.class);
                    intent.putExtra("id", supervisionInspectionVoList.get(position).getId());
                    intent.putExtra("type", type);
                    intent.putExtra("supervisionUnit", getIntent().getStringExtra("supervisionUnit"));
                    intent.putExtra("gradeReportEnclosureVoList", gson.toJson(supervisionInspectionVoList.get(position).getGradeReportEnclosureVoList()));
                    intent.putExtra("supervisionInspectionVo", gson.toJson(supervisionInspectionVoList.get(position)));
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return supervisionInspectionVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_time, tv_speciality, unitAddress, tv_unitName,tv_type,tv_status,tv_legalRepresentative,tv_supervisorName; //
            LinearLayout linearLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_time = itemView.findViewById(R.id.tv_time);
                this.tv_speciality = itemView.findViewById(R.id.tv_speciality);
                this.unitAddress = itemView.findViewById(R.id.unitAddress);
                this.tv_unitName = itemView.findViewById(R.id.tv_unitName);
                this.tv_type=itemView.findViewById(R.id.tv_type);
                this.tv_status=itemView.findViewById(R.id.tv_status);
                this.tv_legalRepresentative=itemView.findViewById(R.id.tv_legalRepresentative);
                this.tv_supervisorName=itemView.findViewById(R.id.tv_supervisorName);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }
}